﻿#include "textbrowsercon.h"
#include <QDateTime>

textBrowserCon::textBrowserCon(QTextBrowser *ui_qtextbrowser)
{
    m_qtextbrowser = ui_qtextbrowser;

}

void formatString(QString &org, int n=2,const QString &ch=" ")
{
    int size= org.size();
    int space= qRound(size*1.0/n+0.5)-1;
    if(space<=0)
        return;
    for(int i=0,pos=n;i<space;++i,pos+=(n+3))
    {
        org.insert(pos,ch);
    }
}

void textBrowserCon::writeAppend(QString text, Qt::Alignment alignment)
{
    formatString(text,30,"\n");

    QStringList textlist = text.split("\n");
    for(int i=0;i<textlist.size();i++)
    {
        m_qtextbrowser->append(textlist[i]);
        QTextCursor storeCursorPos = m_qtextbrowser->textCursor();
        QTextBlockFormat textBlockFormat = storeCursorPos.blockFormat();
        textBlockFormat.setAlignment(alignment);
        storeCursorPos.mergeBlockFormat(textBlockFormat);
        m_qtextbrowser->setTextCursor(storeCursorPos);

    }
}

void textBrowserCon::writeOverLine(QString text, Qt::Alignment alignment)
{
    QTextCursor storeCursorPos = m_qtextbrowser->textCursor();
    storeCursorPos.select(storeCursorPos.LineUnderCursor);
    storeCursorPos.removeSelectedText();
    m_qtextbrowser->moveCursor(storeCursorPos.StartOfLine,storeCursorPos.MoveAnchor);
    m_qtextbrowser->insertPlainText(text);

    QTextBlockFormat textBlockFormat = storeCursorPos.blockFormat();
    textBlockFormat.setAlignment(alignment);
    storeCursorPos.mergeBlockFormat(textBlockFormat);
    m_qtextbrowser->setTextCursor(storeCursorPos);

}

void textBrowserCon::writeTimeStamp()
{
    writeAppend(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss:zzz"),Qt::AlignCenter);

}

void textBrowserCon::clear()
{
    m_qtextbrowser->clear();

}
